# coding=utf-8

from . import admin
from flask import render_template, request, jsonify, make_response, redirect
from dbConnection.MysqlConn import Mysql
from app.MySession import MySession
from app import util
from app.util import login_required
import sys
import time
from app import redis

reload(sys)
sys.setdefaultencoding('utf8')


@admin.route('/')
def hello():
    return login()


# 管理员账户登录
@admin.route('/admin/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        try:
            ip = request.headers.get('X-Real-Ip', request.remote_addr)
            username = request.values.get('username')
            password = request.values.get('password')
            sql = 'select * from admin where username= "%s"' % username
            mysql = Mysql()
            res = mysql.getOne(sql, None)
            if res:
                l = res
                if l['permission'] == 2 or l['login_error'] >= 5:
                    status = 'permission deny ！！！'
                    r_sql = 'insert into login_recoed VALUES (%s,"%s","%s","%s",%s)'\
                            % ('null', username, ip, '账号被锁定', int(time.time()))
                    mysql.insertOne(r_sql, None)
                else:
                    if l['password'] == util.md5(str(password)+l['sole']):
                        r_sql = 'insert into login_recoed VALUES (%s,"%s","%s","%s",%s)' \
                                % ('null', username, ip, '登陆成功', int(time.time()))
                        mysql.insertOne(r_sql, None)
                        count = int(l['login_count']) + 1
                        sql = 'update admin set login_error = 0,login_count = "%s",login_ip = "%s",login_time = %s ' \
                              'where username = "%s"' \
                              % (count, ip, int(time.time()), username)
                        mysql.update(sql, None)
                        status = 'success'
                        data = {
                            'status': status
                        }
                        re = make_response(jsonify(data))
                        user = MySession.create_session(username)
                        re.set_cookie('uid', user)
                        re.set_cookie('user', username)
                        mysql.dispose()
                        return re
                    else:
                        r_sql = 'insert into login_recoed VALUES (%s,"%s","%s","%s",%s)' \
                                % ('null', username, ip, '密码错误', int(time.time()))
                        mysql.insertOne(r_sql, None)
                        count = int(l['login_error']) + 1
                        sql = 'update admin set login_error = "%s",login_ip = "%s",login_time = %s ' \
                              'where username = "%s"' \
                              % (count, ip, int(time.time()), username)
                        mysql.update(sql, None)
                        status = 'error'
            else:
                r_sql = 'insert into login_recoed VALUES (%s,"%s","%s","%s",%s)' \
                        % ('null', username, ip, '账号不存在', int(time.time()))
                mysql.insertOne(r_sql, None)
                status = 'error'
            mysql.dispose()
        except EOFError as e:
            print e
            status = 'error'
        data = {
            'status': status
        }
        return jsonify(data)
    if request.method == 'GET':
        return render_template('login/login.html')


# 登陆首页
@admin.route('/admin/index.html')
@login_required
def login_index():
    return render_template('login/index.html')


# 退出登录
@admin.route('/admin/login_out')
def out():
    uid = request.cookies.get('uid')
    redis.set(uid, '')
    resp = make_response(redirect('/'))
    resp.delete_cookie('uid')
    resp.delete_cookie('user')
    return resp


@admin.route('/admin/update_password', methods=['Post'])
@login_required
def update_password():
    old_password = request.values.get('old_password')
    password = request.values.get('password')
    username = request.cookies.get('user')
    mysql = Mysql()
    sql = 'select * from admin where username = "%s"' % username
    data = mysql.getOne(sql, None)
    old_password = util.md5(str(old_password)+data['sole'])
    sql2 = 'select * from admin where username = "%s" and password = "%s"' % (username, old_password)
    num = mysql.getOne(sql2, None)
    if num is not None:
        password = util.md5(str(password)+data['sole'])
        sql = 'update admin set password = "%s" where username = "%s"' % (password, username)
        data = mysql.update(sql, None)
        if data > 0:
            res = "success"
    else:
        res = "error"
    mysql.dispose()
    return jsonify(res)